﻿/*
 * CanonOscar 0.1
 * Written by (c) agehack a.k.a. GUnitSoldier
 * Released under GNU GPL (http://www.gnu.org/copyleft/gpl.html)
 * 
 * http://www.agehack.pro/oscar
 */
using System;
using Agehack;
namespace Agehack.Icq
{
    public partial class CanonOscar
    {
        /// <summary>
        /// ICQ Functions Manager.
        /// General ICQ engine.
        /// </summary>
        public partial class IcqClient
        {
            #region Fields
            private FlapConnection connection = null;
            private bool authorized = false;
            private ushort currentSequence = 0;
            #endregion
            #region Properties
            public bool IsConnected { get { return authorized && connection != null && connection.IsConnected; } }
            public FlapConnection Connection { get { return connection; } }
            #endregion

            /// <summary>
            /// Initializes new instance of IcqClient class to work with Icq.
            /// </summary>
            public IcqClient() { connection = new FlapConnection(); }

            #region Connection management
            private void SendPacket(Flap pack)
            {
                if (!connection.IsConnected)
                    throw new InvalidOperationException("Cannot send packets without active connection.");

                if (currentSequence >= ushort.MaxValue)
                    currentSequence = 1;
                else
                {
                    if (currentSequence == 0)
                        currentSequence = (ushort)new Random()
                            .Next(1, ushort.MaxValue);
                    else 
                        currentSequence++;
                }

                pack.SequenceNumber = currentSequence;
                connection.Send(pack);
            }
            private Flap ReceivePacket()
            {
                if (!connection.IsConnected)
                    throw new InvalidOperationException("Cannot receive packets without active connection.");

                Flap f = connection.Receive(7);
                return f;
            }
            public void Disconnect()
            {
                if (connection.IsConnected)
                    connection.Disconnect();
                connection = new FlapConnection(); // reset socket
            }
            public static uint RequestID()
            {
                return (uint)new Random(
                    DateTime.Now.Millisecond).Next(242, (int)int.MaxValue);
            }
            #endregion
        }
    }
}
